<template>
  <div>
    <Row>
      <i-col flex="auto">
        <div class="product-item">
          <span style="margin-right: 63px;font-weight: bold">产品分类</span>
          <RadioGroup v-model="product">
            <Radio v-for="(item,index) in product_list" :key="index" :label=item.id>{{item.speaker_name}}</Radio>
          </RadioGroup>
        </div>
      </i-col>
      <i-col>
        <Button icon="md-add" type="success" @click="onClickAddCase">添加</Button>
        <Button icon="md-arrow-round-down" type="primary">导出</Button>
      </i-col>
    </Row>
    <Row>
      <div>
        <ul class="case-module">
          <span style="margin-right: 50px;font-weight: bold">用例模块</span>
          <li>
            <Button type="text" size="small" class="module-btn" @click="setCategory(0), queryCase()" :class="category===0?'onClick':''">全部</Button>
          </li>
          <li v-for="(item,index) in module_list" :key="index">
            <Divider type="vertical" style="margin: 0"/>
            <Button type="text" size="small" class="module-btn" @click="setCategory(item.id), queryCase()" :class="category===item.id?'onClick':''">{{ item.module_name }}</Button>
          </li>
        </ul>
      </div>
    </Row>
    <Row style="margin-top: 20px">
      <i-col span="24">
        <Table height="650" stripe border :columns="table_columns" :data="my_table_data" size="small"></Table>
      </i-col>
    </Row>
    <Modal
        v-model="modal1"
        title="添加用例"
        width="720"
        footer-hide>
        <div>
          <i-form ref="caseInfo" :model="caseInfo" :rules="ruleValidate" :label-width="120">
            <FormItem label="音箱类型" prop="speaker">
              <Select v-model="caseInfo.speaker" placeholder="请选择音箱类型">
                <i-option
                    v-for="(item, index) in product_list"
                    :key="index"
                    :value=item.id>
                      {{ item.speaker_name}}
                </i-option>
              </Select>
            </FormItem>
            <FormItem label="用例模块" prop="module">
              <i-select v-model="caseInfo.module" placeholder="请输入用例模块">
                <i-option
                    v-for="(item, index) in module_list"
                    :key="index"
                    :value=item.id>
                      {{ item.module_name }}
                </i-option>
              </i-select>
            </FormItem>
            <FormItem label="执行语句" prop="case_query">
              <i-input v-model="caseInfo.case_query" placeholder="请输入执行语句"></i-input>
            </FormItem>
            <FormItem label="期望Domain" prop="ex_domain">
              <i-input v-model="caseInfo.ex_domain" placeholder="请输入期望Domain"></i-input>
            </FormItem>
            <FormItem label="期望Intent" prop="ex_intent">
              <i-input v-model="caseInfo.ex_intent" placeholder="请输入期望Intent"></i-input>
            </FormItem>
            <FormItem label="TTS关键字">
              <i-input v-model="caseInfo.tts_keywords" placeholder="请输入TTS关键字"></i-input>
            </FormItem>
            <FormItem label="用例类型" prop="is_smoke">
              <RadioGroup v-model="caseInfo.is_smoke">
                <Radio label="true">冒烟用例</Radio>
                <Radio label="false">普通用例</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="前置query">
              <i-input v-model="caseInfo.setup_query" placeholder="请输入前置query"></i-input>
            </FormItem>
            <FormItem label="后置query">
              <i-input v-model="caseInfo.end_query" placeholder="请输入后置query"></i-input>
            </FormItem>
            <FormItem label="音箱动作" prop="actions">
              <Tooltip placement="top" content="请保证每条actions为单独一行！" style="width: 100%">
                <i-input
                    v-model="caseInfo.actions"
                    type="textarea"
                    :autosize="{minRows: 2,maxRows: 10}"
                    placeholder="请填写断言音箱动作关键字"
                ></i-input>
              </Tooltip>
            </FormItem>
            <FormItem>
              <Row>
                <i-col flex="auto">
                </i-col>
                <i-col flex="160px">
                  <i-button @click="handleReset('caseInfo')" style="margin-left: 8px">清空</i-button>
                  <i-button type="primary" @click="handleSubmit('caseInfo')">提交</i-button>
                </i-col>
              </Row>
            </FormItem>
          </i-form>
        </div>
    </Modal>
  </div>
</template>

<script>
export default {
  name: "TestCase",
  data() {
    return{
      category: 0,
      product: 1,
      modal1: false,
      table_columns: [
        {
          title: '用例编号',
          key: 'id',
          width: '100',
          align: 'center'
        },
        {
          title: '执行语句',
          key: 'case_query',
          width: '180',
          align: 'center'
        },
        {
          title: '期望Domain',
          key: 'ex_domain',
          width: '200',
          align: 'center'
        },
        {
          title: '期望Intent',
          key: 'ex_intent',
          width: '190',
          align: 'center'
        },
        {
          title: 'TTS关键字',
          key: 'tts_keywords',
          width: '190',
        },
        {
          title: '音箱动作',
          key: 'speaker_actions'
        },
        {
          title: '前置query',
          key: 'setup_query'
        },
        {
          title: '后置query',
          key: 'end_query'
        },
        {
          title: '类型',
          key: 'is_smoke',
          width: '90',
          align: 'center',
          render: (h, params) => {
            const row = params.row;
            const color = row['is_smoke'] ? 'success' : 'default';
            const text = row['is_smoke'] ? '冒烟' : '普通';

            return h('Tag', {
              props: {
                type: 'border',
                color: color
              }
            }, text);
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'info',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.execute(params.index)
                  }
                }
              }, '执行'),
              h('Button', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.show(params.index)
                  }
                }
              }, '编辑'),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.remove(params.row.id)
                  }
                }
              }, '删除')
            ]);
          }
        }
      ],
      table_data: [
        {
          name: 'John Brown',
          age: 18,
          address: 'New York No. 1 Lake Park',
          date: '2016-10-03'
        },
        {
          name: 'Jim Green',
          age: 24,
          address: 'London No. 1 Lake Park',
          date: '2016-10-01'
        },
        {
          name: 'Joe Black',
          age: 30,
          address: 'Sydney No. 1 Lake Park',
          date: '2016-10-02'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        },
        {
          name: 'John Brown',
          age: 18,
          address: 'New York No. 1 Lake Park',
          date: '2016-10-03'
        },
        {
          name: 'Jim Green',
          age: 24,
          address: 'London No. 1 Lake Park',
          date: '2016-10-01'
        },
        {
          name: 'Joe Black',
          age: 30,
          address: 'Sydney No. 1 Lake Park',
          date: '2016-10-02'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        },
        {
          name: 'Jon Snow',
          age: 26,
          address: 'Ottawa No. 2 Lake Park',
          date: '2016-10-04'
        }
      ],
      my_table_data: [],
      product_list: [],
      module_list: [],
      caseInfo: {
        case_query: '',
        ex_domain: '',
        ex_intent: '',
        tts_keywords: '',
        speaker: 1,
        setup_query: '',
        end_query: '',
        module: -1,
        is_smoke: 'true',
        actions: ''
      },
      ruleValidate: {
        case_query: [
          { required: true, message: '请输入执行语句', trigger: 'blur' }
        ],
        ex_domain: [
          { required: true, message: '请输入期望Domain', trigger: 'blur' }
        ],
        ex_intent: [
          { required: true, message: '请输入期望intent', trigger: 'blur' }
        ],
        speaker: [
          { required: true, type:'number', message: '请选择音箱类型', trigger: 'change' }
        ],
        module: [
          { required: true, type:'number', message: '请选择用例模块', trigger: 'change' }
        ],
        is_smoke: [
          { required: true, message: '请输入用例类型', trigger: 'change' }
        ],
        actions: [
          { required: true, message: '请输入音箱动作', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 获取产品列表
    this.$getRequest('/speakerProduct').then( response => {
      if (response) {
        //  这里需要使用vuex来保存response数据，这里为了方便，直接放在sessionStorage里面了
        sessionStorage.setItem('module_info', JSON.stringify(response.data))
        this.product_list = response.data
        this.module_list = response.data[0].modules
        this.product = response.data[0].id
        this.queryCase();
      }
    }).catch( error => {
      console.log(error)
    });
  },
  watch: {
    product(newName, oldName) {
      let module_info = sessionStorage.getItem('module_info')

      // 从sessionStorage中读取数据，遍历数据
      JSON.parse(module_info).forEach(item=>{
        if (item.id === newName){
          this.module_list = item.modules
        }
      })
    },
    "caseInfo.speaker":function(newValue, oldValue){
      let s_info = sessionStorage.getItem('module_info')
      // 从sessionStorage中读取数据，遍历数据
      JSON.parse(s_info).forEach(item=>{
        if (item.id === newValue){
          this.module_list = item.modules
        }
      })
    }
  },
  methods:{
    onClickAddCase(){
      this.modal1 = true
      this.handleReset("caseInfo")
    },
    show (index) {
      this.$Modal.info({
        title: 'User Info',
        content: `Name：${this.table_data[index].name}<br>Age：${this.table_data[index].age}<br>Address：${this.table_data[index].address}`
      })
    },
    execute(index) {
      this.$Modal.info({
        title: '执行信息',
        content: `Name：${this.table_data[index].name}<br>Age：${this.table_data[index].age}<br>Address：${this.table_data[index].address}`
      })
    },
    remove (id) {
      this.$Modal.confirm({
        title: '信息',
        content: '<p>确定删除该用例？</p>',
        loading: true,
        onOk: () => {
          // 这里添加ajax请求 TODO
          this.$deleteRequest(`/testcase/delete/${id}`).then( response => {
            if (response.status === 200) {
              this.$Message.info(response.data.message)
              location.reload()
            }
          }).catch( error => {
            console.log(error)
          })
          this.$Modal.remove();
        }
      });
    },
    setCategory(param) {
      this.category = param
    },
    queryCase () {
      // 获取所有数据
      this.$getRequest(`/testcase/?product_id=${this.product}&module_id=${this.category}`).then( response => {
        if (response) {
          this.my_table_data = response.data
        }
      }).catch( error => {
        console.log(error)
      })
    },
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$Modal.confirm({
            title: '信息',
            content: '<p>确认是否添加用例？</p>',
            loading: true,
            onOk: () => {
              this.$postRequest(`/testcase/add/`, this.caseInfo).then( response => {
                if (response) {
                  this.$Message.info('入库成功！');
                  location.reload()
                }
              }).catch( error => {
                console.log(error)
              })
              this.$Modal.remove();
              this.modal1 = false
            }
          });
        } else {
          this.$Message.error('参数填写错误，请重新填写！');
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields();
    }
  }
}
</script>

<style scoped>
.product-item,.case-module{
  margin-top: 10px;
}
.case-module, li{
  display: inline-block;
}
.module-btn{
  border-radius: 10px;
}
.onClick{
  background-color: #d5e8fc;
}

</style>